Remove Duplicates from Sorted Array

Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this in place with constant memory.
Given input array nums = [1,1,2],
Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.
It doesn't matter what you leave beyond the new length.

题目大意:给定已排序数组,移除其中的重复元素,返回新数组长度,要求移除操作在原数组上进行,空间复杂度O(1),数组可以有残留数字

题目难度:Easy

/**
 * Created by gzdaijie on 16/5/8
 * 相邻2个数比较,不相同时,计数,新的数覆盖重复的数
 */
public class Solution {
    public int removeDuplicates(int[] nums) {
        if (nums == null || nums.length == 0) return 0;

        int len = nums.length;
        int k = 1;
        for (int i = 0; i < len - 1; i++) {
            if (nums[i] != nums[i + 1]) {
                nums[k++] = nums[i + 1];
            }
        }
        return k;
    }
}
gzdaijie            updated 2016-05-08 01:48:17

results matching ""

    No results matching ""